<template>
    <div id="sockAll">
        <ul id="messages">
            <li v-for="item in messageList" :key="item" :class="username === item.username ? 'mainer' : 'other'">
                <div class="avatar">
                    <template v-if="username === item.username">
                        <img src="../../../../assets/images/userImage.webp" alt="" />
                    </template>
                    <template v-else>
                        <img src="../../../../assets/images/userImage.webp" alt="" />
                    </template>
                </div>
                <div class="words">
                    <span v-if="!item.isImage">
                        {{ item.message }}
                    </span>
                    <img v-if="item.isImage" :src="item.message" alt="">
                </div>
            </li>
        </ul>
        <div id="saying" :style="{ opacity: isSpeaking ? 1 : 0 }">
            <img src="@/assets/images/yuyin.gif" alt="">
        </div>
        <div id="nav_bottom">
            <form id="form" @submit.prevent="sendOnEnter">
                <input id="input" autocomplete="off" v-model="dispatcher" @keyup.enter="sendOnEnter"
                    @keydown.enter.prevent />
                <button @click.prevent="openEmoji">
                    <img src="@/assets/images/emoji.png" alt="" />
                </button>
                <template v-if="dispatcher.length > 0">
                    <button @click.prevent="send">发送</button>
                </template>
                <template v-else>
                    <button @click.prevent="openPopup">
                        <img src="@//assets/images/plus.png" alt="" />
                    </button>
                </template>
            </form>
            <div id="popup" :style="{ display: flag }">
                <van-grid :border="false" :gutter="5">
                    <van-grid-item icon="photo-o" text="图片" @click="selectImage" />
                    <van-grid-item icon="volume-o" text="转文字" @touchstart="toggleSpeechRecognition" @touchend="btnup" />
                    <van-grid-item icon="photo-o" text="文字" />
                    <van-grid-item icon="photo-o" text="文字" />
                </van-grid>
            </div>
            <div id="emoji" :style="{ display: flag1 }">
                <div v-for="row in emojilist" :key="row" style="display: flex; justify-content: space-between;">
                    <div v-for="emoji in row" :key="emoji" @click="dispatcher += emoji">
                        {{ emoji }}
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { io } from 'socket.io-client';
import axios from 'axios';
import { ref, defineProps } from 'vue';
//语音转文字
//测试语音识别
// const prompt = ref('')
const isSpeaking = ref(false);
let recognition = null; // 语音识别对象
let finalResult = ''; // 保存最终结果的变量
let interimResult = ''; // 保存中间结果的变量
const toggleSpeechRecognition = () => {
    if (!recognition) {
        recognition = new webkitSpeechRecognition();
        recognition.continuous = true;
        recognition.interimResults = true;
        recognition.lang = 'zh-CN';
        recognition.onresult = event => {
            interimResult = ''; // 清空中间结果
            for (let i = event.resultIndex; i < event.results.length; i++) {
                if (event.results[i].isFinal) {
                    finalResult += event.results[i][0].transcript;
                } else {
                    interimResult += event.results[i][0].transcript;
                }
            }
            // prompt.value = finalResult + interimResult;
            dispatcher.value = finalResult + interimResult;
        };
        recognition.start();
        isSpeaking.value = true;
    }
};
const btnup = () => {
    if (recognition) {
        recognition.stop();
        isSpeaking.value = false;
        recognition = null;
        finalResult = '';
        interimResult = '';
        dispatcher.value = ''
    }
};

//emoji表情
const emojilist = ref([
    ['😀', '😁', '😂', '🤣', '😃', '😅', '😆'],
    ['😉', '😊', '😋', '😎', '😍', '😘', '😗'],
    ['😙', '😚', '🙂', '🤗', '🤔', '😐', '😑'],
    ['😶', '🙄', '😏', '😣', '😥', '😮', '🤐'],
    ['😯', '😪', '😫', '😴', '😌', '😛', '😜'],
    ['😝', '🤤', '😒', '😓', '😔', '😕', '🙃'],
    ['🤑', '😲', '🙁', '😖', '😟', '😤', '😢'],
    ['😭', '😧', '😨', '😩', '😬', '😰', '😳'],
    ['😱', '😵', '😡', '😠', '😷', '🤒', '🤕'],
]);

const flag = ref('none');
const flag1 = ref('none');

//展开底部导航
const openPopup = () => {
    if (flag.value === 'none') {
        flag.value = 'block';
        flag1.value = 'none';
    } else {
        flag.value = 'none';
        flag1.value = 'block';
    }
};
//展开表情导航
const openEmoji = () => {
    if (flag1.value === 'none') {
        flag1.value = 'block';
        flag.value = 'none';
    } else {
        flag1.value = 'none';
        flag.value = 'block';
    }
};

const sendOnEnter = (event) => {
    if (event.key === 'Enter' && !event.shiftKey) {
        send();
        event.preventDefault();
    }
};

const props = defineProps({
    username: String,
});

const messageList = ref([]);
const dispatcher = ref('');

const socket = io('ws://127.0.0.1:3001');

socket.on('connection', (socket) => {
    console.log('a user connected');
    socket.on('disconnect', () => {
        console.log('user disconnected');
    });
});

socket.on('message', (socket, user) => {
    let userobj = {
        username: user,
        message: socket,
    };
    messageList.value.push(userobj);
    console.log(messageList.value);
});
socket.on('imageMessage', (data) => {
    console.log('Received image message: ', data);
    const imgBaseUrl = "http://localhost:3001/uploads";
    const imageName = data.path.split("\\").pop();
    const imageUrl = imgBaseUrl + '/' + imageName;
    // url.value = imageUrl
    console.log('最终路径', imageUrl);
    // 根据实际情况判断发送者
    let sender = data.username ? data.username : props.username;
    let userobj = {
        username: sender,
        message: imageUrl,
        isImage: data.isUploaded || false,
    };
    messageList.value.push(userobj);
    console.log(messageList.value);
});

const send = () => {
    if (dispatcher.value) {
        socket.emit('message', dispatcher.value, props.username);
        dispatcher.value = '';
        flag.value = 'none';
        flag1.value = 'none';
    }
};

const selectImage = () => {
    const input = document.createElement('input');
    input.type = 'file';
    input.accept = 'image/*';
    input.onchange = async (event) => {
        const file = event.target.files[0];
        if (file) {
            const formData = new FormData();
            formData.append('image', file);
            // 添加用户信息到请求数据中
            formData.append('username', props.username);
            try {
                await axios.post('http://127.0.0.1:3001/upload', formData, {
                    headers: {
                        'Content-Type': 'multipart/form-data',
                    },
                });
            } catch (error) {
                console.error('上传图片失败：', error);
            }
        }
    };
    input.click();
};


</script>

<style>
#sockAll {
    margin: 0;
    padding-bottom: 3rem;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
    height: 100%;
    width: 100%;
}

#saying {
    width: 90%;
    height: 150px;
    background: pink;
    position: fixed;
    bottom: 250px;
    left: 22px;
    z-index: 10000;

    img {
        width: 100%;
        height: 100%;
    }
}

#nav_bottom {
    width: 100%;
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    border-top: 1px solid #ccc;
    align-items: center;
    justify-content: center;
    background: white;

    #form {
        width: 100%;
        background: rgb(205, 203, 203);
        padding: 0.25rem;
        display: flex;
        height: 3rem;
        box-sizing: border-box;
        backdrop-filter: blur(10px);
    }

    #input {
        border: none;
        padding: 0 1rem;
        flex-grow: 1;
        border-radius: 2rem;
        margin: 0.25rem;
    }

    #input:focus {
        outline: none;
    }

    #form>button {
        background: #333;
        border: none;
        padding: 0 1rem;
        margin: 0.25rem;
        border-radius: 3px;
        outline: none;
        color: #fff;

        img {
            width: 25px;
            height: 25px;
            margin-top: 3px;
        }
    }

    #popup {
        width: 100%;
        height: 150px;
        padding-top: 30px;
    }

    #emoji {
        width: 100%;
        height: 150px;
    }
}

#messages {
    list-style-type: none;
    margin: 0;
    padding: 0;

    li {
        display: flex;
    }
}

.mainer {
    width: 100%;
    min-height: 50px;
    text-align: right;
    flex-direction: row-reverse;
    margin-bottom: 20px;

    .avatar {
        width: 50px;
        height: 50px;

        img {
            width: 100%;
            height: 100%;
        }
    }

    .words {
        max-width: 60%;
        height: auto;
        background: #95ec69;
        text-align: left;
        margin-right: 20px;
        border-radius: 10px;
        line-height: 2em;
        padding: 10px;

        img {
            width: 140px;
            height: 100px;
        }
    }
}

.other {
    width: 100%;
    height: auto;
    margin-bottom: 20px;

    .avatar {
        width: 50px;
        height: 50px;

        img {
            width: 100%;
            height: 100%;
        }
    }

    .words {
        max-width: 60%;
        height: auto;
        background: #ffffff;
        text-align: left;
        margin-left: 20px;
        border-radius: 10px;
        line-height: 2em;
        padding: 10px;

        img {
            width: 140px;
            height: 100px;
        }
    }
}
</style>

<!-- 1 -->